package com.thinvent.recommend.manager.manager.impl;

import com.thinvent.recommend.manager.dto.KbFileContentDTO;
import com.thinvent.recommend.manager.manager.DocumentIndexManager;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.store.Directory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Lucene TF–IDF 索引管理器实现
 */
@Component
public class DocumentIndexManagerImpl implements DocumentIndexManager {

    @Autowired
    private Directory directory;           // 在 LuceneConfig 中注入的索引目录

    @Autowired
    private Analyzer jiebaAnalyzer;        // 自定义的 JiebaAnalyzer

    @Override
    public void rebuildIndex(List<KbFileContentDTO> docs) throws Exception {
        // 使用 JiebaAnalyzer 的配置来构建 IndexWriter
        IndexWriterConfig cfg = new IndexWriterConfig(jiebaAnalyzer);
        // 每次都删除旧索引，重新创建
        cfg.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

        try (IndexWriter writer = new IndexWriter(directory, cfg)) {
            for (KbFileContentDTO dto : docs) {
                Document doc = new Document();
                // 文档业务 ID
                doc.add(new StringField("id", dto.getId(), Field.Store.YES));
                // content 字段：存储原文并保留 termVectors 以便调试
                FieldType ft = new FieldType(TextField.TYPE_STORED);
                ft.setStoreTermVectors(true);
                ft.setStoreTermVectorPositions(true);
                ft.setStoreTermVectorOffsets(true);
                doc.add(new Field("content", dto.getContent(), ft));
                writer.addDocument(doc);
            }
            // 提交并关闭
            writer.commit();
        }
    }
}
